package me.wanghongyu.railwayquery.view;

import lombok.SneakyThrows;
import me.wanghongyu.railwayquery.model.Ticket;
import me.wanghongyu.railwayquery.model.TrainInfo;
import me.wanghongyu.railwayquery.utils.QueryUtils;
import me.wanghongyu.railwayquery.utils.StringUtils;
import me.wanghongyu.railwayquery.view.event.LocationChangeEvent;

import java.awt.event.*;
import java.io.IOException;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;


public class QueryView extends JFrame{
	
	
	private JLabel departureLabel;
	private JComboBox<String> departureInput;
	private JLabel destinationLabel;
	private JComboBox<String> destinationInput;
	private JButton queryButton;
	private ResultTable resultTable;
	private JScrollPane scrollPane;
	private JComboBox<String> dateSwitch;
	private JCheckBox studentCheck;

	public QueryView(){
		setTitle("铁路信息查询");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setResizable(false);
		setLayout(null);
		try {
			addButton();
		} catch (IOException | URISyntaxException e) {
			e.printStackTrace();
		}
		setSize(900, 600);
		setVisible(true);
	}

	@SneakyThrows
	public void addButton() throws IOException, URISyntaxException {

		/*
		出发地输入
		 */

		departureLabel = (JLabel) createComponent(JLabel.class, 140, 10, 50, 30);
		departureLabel.setText("出发地");
		add(departureLabel);
		
		departureInput = (JComboBox<String>) createComponent(JComboBox.class, 200, 10, 100, 30);
		departureInput.setEditable(true);
		departureInput.getEditor().getEditorComponent().addKeyListener(new LocationChangeEvent(departureInput));
		add(departureInput);


		/*
		目的地输入
		 */

		destinationLabel = (JLabel) createComponent(JLabel.class, 330, 10, 50, 30);
		destinationLabel.setText("目的地");
		add(destinationLabel);

		destinationInput = (JComboBox<String>) createComponent(JComboBox.class, 380, 10, 100, 30);
		destinationInput.setEditable(true);
		destinationInput.getEditor().getEditorComponent().addKeyListener(new LocationChangeEvent(destinationInput));
		add(destinationInput);


		/*
		日期选择
		 */

		destinationLabel = (JLabel) createComponent(JLabel.class, 510, 10, 50, 30);
		destinationLabel.setText("日期");
		add(destinationLabel);

		dateSwitch = (JComboBox<String>) createComponent(JComboBox.class,560,10,100,30);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		for (int i = 0; i < 14; i++) {
			dateSwitch.addItem(format.format(new Date(System.currentTimeMillis() + i * 1000 * 60 * 60 * 24)));
		}


		add(dateSwitch);
		
		queryButton = (JButton) createComponent(JButton.class, 300, 50, 100, 50);
		queryButton.setText("查询");
		/*
		输入检查
		 */
		queryButton.addActionListener(e -> {
			String start = departureInput.getEditor().getItem().toString();
			String end = destinationInput.getEditor().getItem().toString();
			if(start.length() == 0 || end.length() == 0){
				message("有内容没输入!");
				return;
			}
			if(!QueryUtils.getDataCache().containsKey(start) || !QueryUtils.getDataCache().containsKey(end)){
				message("你填的车站不存在!");
				return;
			}
			scrollPane.remove(resultTable);
			try {
				scrollPane.setViewportView(new ResultTable(start,end,dateSwitch.getSelectedItem().toString(),studentCheck.isSelected()));
			} catch (IOException | URISyntaxException ioException) {
				ioException.printStackTrace();
			}
			scrollPane.validate();
		});
		add(queryButton);

		/*
		学生票勾选框
		 */
		studentCheck = (JCheckBox) createComponent(JCheckBox.class,450,50,100,50);
		studentCheck.setText("学生价格");
		add(studentCheck);

		/*
		车次表格
		 */

		resultTable = new ResultTable();
		scrollPane = new JScrollPane(resultTable);
		scrollPane.setBounds(0, 150, 900, 400);
		add(scrollPane);
	}
	
	public JComponent createComponent(Class<? extends JComponent> cClass,int x,int y,int width,int height) {
		try {
			JComponent jComponent = cClass.newInstance();
			jComponent.setBounds(x, y, width, height);
			return jComponent;
		} catch (InstantiationException | IllegalAccessException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void message(String msg){
		JOptionPane.showMessageDialog(null, msg, "", JOptionPane.INFORMATION_MESSAGE);
	}

}

/*
车次表格
 */

class ResultTable extends JTable{

	DefaultTableModel defaultModel;

	public ResultTable(){
		setEnabled(false);
		setBounds(0, 0, 900, 400);
	}

	public ResultTable(String start,String end,String date,boolean isStudent) throws IOException, URISyntaxException {
		this();
		List<TrainInfo> trainInfoList = QueryUtils.getTrainInfo(start, end,date,isStudent);
		if(trainInfoList == null){
			return;
		}
		if(trainInfoList.size() == 0){
			QueryView.message("当天已经没车了!");
			return;
		}
		String[] name = {"车次","开始点","结束点","开始时间","到达时间","用时"};
		String[][] data = new String[trainInfoList.size()][6];
		for (int i = 0; i < trainInfoList.size(); i++) {
			TrainInfo train = trainInfoList.get(i);
			data[i][0] = train.getNumber();
			data[i][1] = train.getStart();
			data[i][2] = train.getEnd();
			data[i][3] = train.getStartTime();
			data[i][4] = train.getEndTime();
			data[i][5] = train.getTime() + "分钟";
		}
		/*
		统计车票
		 */
		Map<String,List<String>> seatMap = new LinkedHashMap<>();
		
		Set<String> seatSet = new HashSet<>();
		for(TrainInfo trainInfo: trainInfoList) {
			for (Ticket ticket : trainInfo.getTicketList()) {
				seatSet.add(ticket.getName());
			}
		}

		for(TrainInfo trainInfo: trainInfoList){
			for (String seat : seatSet) {
				List<String> list = new ArrayList<>();;
				if(seatMap.containsKey(seat)){
					list = seatMap.get(seat);
				}
				Ticket ticket = trainInfo.containTicket(seat);
				if(ticket == null){
					list.add(null);
					continue;
				}
				list.add(ticket.getPrice() + "元/" + (ticket.getAmount() == 99 ? "有票" : "剩" + ticket.getAmount() + "张"));
				seatMap.put(seat,list);
			}
		}
		defaultModel = new DefaultTableModel(data,name);
		for (String s : seatMap.keySet()) {
			List<String> list = seatMap.get(s);
			defaultModel.addColumn(s,list.toArray(new String[list.size()]));
		}
		setModel(defaultModel);
	}
}

